import { Feature, Overlay } from "ol";
import { createFeature } from "../create/createFeature";
import {
  createMultiPointGeometry,
  createPointGeometry,
} from "../create/createGeometry";
import { createVectorLayer } from "../create/createLayer";
import { createSource } from "../create/createSource";
import {
  PointStyleOptions,
  PointType,
  createPointStyle,
} from "../styles/pointsStyle";
import { transform4326to3857 } from "../utils/transform";
import { Coordinate } from "ol/coordinate";

type OverlayOptions = ConstructorParameters<typeof Overlay>[0];
export interface CreateOverlayOptions<T> {
  getLngKey?: keyof T;
  getLatKey?: keyof T;
  html: string | ((data: T) => string);
  overlayOptions?: OverlayOptions | ((data: T) => OverlayOptions);
}

export function createOverlay<T>(data: T[], options?: CreateOverlayOptions<T>) {
  const overlays: Overlay[] = [];
  const {
    getLngKey = "lng",
    getLatKey = "lat",
    html = "",
    overlayOptions = {},
  } = options || {};
  const points: Coordinate[] = [];
  data.forEach((item) => {
    const lng = item[getLngKey as keyof T];
    const lat = item[getLatKey as keyof T];
    if (lng !== undefined && lat !== undefined) {
      const coordinate = transform4326to3857([lng as number, lat as number]);

      const element = document.createElement("div");
      // 创建覆盖物元素
      if (typeof html === "function") {
        element.innerHTML = html(item);
      } else if (typeof html === "string") {
        element.innerHTML = html;
      }

      let overlayOpts: OverlayOptions = {};
      if (typeof overlayOptions === "function") {
        overlayOpts = overlayOptions(item);
      } else if (typeof overlayOptions === "object") {
        overlayOpts = overlayOptions;
      }

      // 创建覆盖物对象
      const overlay = new Overlay({
        position: coordinate, // 经纬度坐标转换为地图坐标
        positioning: "center-center", // 覆盖物的定位方式
        element: element, // 覆盖物的内容
        stopEvent: true, // 是否阻止事件冒泡到地图上
        ...overlayOpts,
      });

      overlays.push(overlay);
    }
  });

  return overlays;
}
